package projectmanagement.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import projectmanagement.model.Person;
import projectmanagement.util.ApplicationSecurityManager;
import projectmanager.model.dao.PersonDao;

public class EnterPersonController extends SimpleFormController {
	public static final String PERSON_ID = "id";
	public static final String ACTION = "action";
	public static final String ACTION_NEW = "new";
	public static final String ACTION_EDIT = "edit";

	private PersonDao personManager;
	private ApplicationSecurityManager applicationSecurityManager;

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {

		String id = request.getParameter(PERSON_ID);
		String action = request.getParameter(ACTION);

		if (action != null && action.length() > 0) {
			if (action.equals(ACTION_EDIT) && id != null
					&& id.trim().length() > 0) {
				Person person = this.personManager.getPersonById(Integer
						.parseInt(id));
				return person;
			} else if (action.equals(ACTION_NEW) && id == null) {
				return new Person();
			} else {
				throw new ServletException();
			}
		}

		return null;
	}

	public void onBindAndValidate(HttpServletRequest request, Object command,
			BindException errors) throws Exception {
		if (errors.hasErrors())
			return;

		Person person = (Person) command;
		String action = request.getParameter(ACTION);

		if (action != null && action.length() > 0) {
			personManager.save(person);
		} else {
			throw new ServletException();
		}
	}

	public ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		return new ModelAndView(getSuccessView());
	}

	public PersonDao getPersonManager() {
		return personManager;
	}

	public void setPersonManager(PersonDao personManager) {
		this.personManager = personManager;
	}

	public ApplicationSecurityManager getApplicationSecurityManager() {
		return applicationSecurityManager;
	}

	public void setApplicationSecurityManager(
			ApplicationSecurityManager applicationSecurityManager) {
		this.applicationSecurityManager = applicationSecurityManager;
	}

}
